package binarytree;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/24 21:53
 * https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/
 * 将有序数组转换为平衡二叉搜索树
 */
public class SortedArrayToBST {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums.length == 1) {
            return new TreeNode(nums[0]);
        }
        return traversal(nums, 0, nums.length - 1);
    }

    public static TreeNode traversal(int[] nums, int left, int end) {
        if (left >= end) {
            return null;
        }
        int mid = (left + end) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = traversal(nums, left, mid - 1);
        root.right = traversal(nums, mid + 1, end);
        return root;
    }

    public static void main(String[] args) {

    }
}
